<script setup>
import { Upload, VideoPause, VideoPlay, Delete, Share } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { shortPlayApi } from '@/api/shortPlay'
import { getSocialUserPage } from '@/api/system/social/user'
import { uploadApi } from '@/api/system/upload/chunkUpload'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { config } from '@/config/axios/config'

const submiting = ref(false)

// 上传表单数据
const uploadForm = reactive({
  playletId: '',
  socialUserId: '',
  fileId: null,
  videoRemark: '',
  publishType: '1',
  cron: '',
  title: ''
})

// 上传进度状态
const uploadProgress = ref(0)
const currentUploadTask = ref({
  completedChunks: 0,
  progress: 0
})
const isUploading = ref(false)
const isShowProgress = ref(false) // 是否显示上传进度条

// 短剧选项
const dramaOptions = ref([])

// 账号选项
const channelOptions = ref([])

// 任务列表
const taskList = ref([
  {
    id: 1,
    name: '重生之逆袭人生',
    fileName: 'episode_15.mp4',
    channel: '主话题频号',
    status: 'uploading',
    progress: 65
  },
  {
    id: 2,
    name: '萌宝助攻：爹地快追妈咪',
    fileName: 'episode_22.mp4',
    channel: '短剧账号A',
    status: 'completed',
    progress: 100
  },
  {
    id: 3,
    name: '穿越之皇后万福',
    fileName: 'episode_10.mp4',
    channel: '主话题频号',
    status: 'completed',
    progress: 100
  }
])

const chunkSize = 1024 * 1024 * 6 // 4MB
const worker = ref(null)

// 文件选择处理
const handleFileChange = (file) => {
  console.log('file', file)
  // uploadForm.file = file.raw
  if (file.status === 'ready') {
    // 验证文件
    if (file.raw.size > 1024 * 1024 * 128) {
      ElMessage.warning('文件大小不能超过128MB')
      return
    }
    // 开始分片
    uploadProgress.value = 0
    isUploading.value = true
    const chunkArr = creatChunks(file.raw, chunkSize)
    console.log('chunkArr', chunkArr)
    let firstChunk = chunkArr.shift()
    // 上传第一个获取uploadId，然后多线程上传
    isUploading.value = true
    uploadApi
      .chunkUpload({
        name: file.raw.name,
        size: file.raw.size,
        directory: 'dy',
        type: file.raw.type,
        chunkSize: firstChunk.size,
        totalChunks: chunkArr.length + 1,
        chunkNumber: 1,
        chunkContent: firstChunk,
        uploadId: null
      })
      .then((res) => {
        console.log('上传', res)
        currentUploadTask.value.completedChunks++  // 第一片成功
        currentUploadTask.value.progress = currentUploadTask.value.completedChunks / chunkArr.length
        renderWorker(chunkArr, {
          uploadId: res.data.uploadId,
          name: file.raw.name,
          size: file.raw.size,
          type: file.raw.type
        })
      })
  }
}

function renderWorker(chunkArr, params) {
  // 如果已有worker存在，先终止它
  if (worker.value) {
    worker.value.terminate()
  }

  worker.value = new Worker('/worker.js')

  // 重置上传状态
  uploadProgress.value = 0
  isUploading.value = true

  // 创建新的上传任务
  if (chunkArr && chunkArr.length > 0) {
    const newTask = {
      id: Date.now(),
      fileName: params.name,
      status: 'uploading',
      progress: 0,
      totalChunks: chunkArr.length,
      completedChunks: 0
    }

    currentUploadTask.value = newTask

    // 将任务添加到任务列表（这里可以根据需要决定是否添加到现有的taskList中）
    // taskList.value.unshift(newTask);

    // 发送分片数据到worker
    worker.value.postMessage({
      type: 'uploadChunks',
      chunks: chunkArr,
      params,
      Authorization: 'Bearer' + getAccessToken(),
      url: config.base_url + '/infra/file-chunk-upload/upload'
    })
    // 接收来自工作线程的消息
    worker.value.onmessage = function (e) {
      const { type, data } = e.data
      console.log('worker.value.onmessage', data)
      if (data.fileId) {
        uploadForm.fileId = data.fileId
      }

      switch (type) {
        case 'chunkComplete':
          console.log('分片上传完成:', data)
          if (currentUploadTask.value) {
            currentUploadTask.value.completedChunks++
            currentUploadTask.value.progress = data.progress
            uploadProgress.value = data.progress

            // 可以在这里更新UI，显示每个分片的上传状态
            console.log('uploadProgress', uploadProgress.value)
            // ElMessage.info(`分片 ${data.chunkIndex + 1}/${currentUploadTask.value.totalChunks} 上传完成`);
          }
          break

        case 'chunkError':
          console.error('分片上传错误:', data)
          uploadProgress.value = 0
          isUploading.value = false
          ElMessage.error(`分片 ${data.chunkIndex + 1} 上传失败: ${data.error}`)
          if (currentUploadTask.value) {
            currentUploadTask.value.status = 'failed'
          }
          break

        case 'allComplete':
          console.log('所有分片上传完成')
          if (currentUploadTask.value) {
            currentUploadTask.value.status = 'completed'
            currentUploadTask.value.progress = 100
            uploadProgress.value = 100
          }
          isUploading.value = false
          ElMessage.success('文件上传成功')
          break

        case 'cancelled':
          console.log('上传已取消')
          if (currentUploadTask.value) {
            currentUploadTask.value.status = 'cancelled'
          }
          isUploading.value = false
          ElMessage.info('上传已取消')
          break
      }
    }
    // 接收来自工作线程的错误消息
    worker.value.onerror = function (e) {
      console.error('Worker错误:', e.message)
      ElMessage.error(`Worker执行错误: ${e.message}`)
      isUploading.value = false
      uploadProgress.value = 0
      if (currentUploadTask.value) {
        currentUploadTask.value.status = 'failed'
      }
    }
  }
}

// 取消上传
function cancelUpload() {
  if (worker.value) {
    worker.value.postMessage({
      type: 'cancel'
    })
    worker.value.terminate()
    worker.value = null
  }
  isUploading.value = false
  if (currentUploadTask.value) {
    currentUploadTask.value.status = 'cancelled'
  }
}

// 创建分片
function creatChunks(file, _chunkSize) {
  const chunkArr = []
  for (let i = 0; i < file.size; i += _chunkSize) {
    chunkArr.push(file.slice(i, i + _chunkSize))
  }
  return chunkArr
}

// 保存草稿
const saveDraft = () => {
  console.log('uploadForm', uploadForm)
  
  validate().then(res => {
    submiting.value = true
    uploadApi
      .dyPublish({
        playletId: uploadForm.playletId,
        socialUserId: uploadForm.socialUserId,
        fileId: uploadForm.fileId,
        videoRemark: uploadForm.videoRemark,
        publishType: uploadForm.publishType,
        cron: uploadForm.cron
      })
      .then((res) => {
        console.log('res', res)
        // window.open(res, '_blank')
        ElMessage.success('已保存，可到发布管理查看')
      })
      .finally(() => {
        submiting.value = false
        isUploading.value = false
        uploadProgress.value = 0
        //  重置表单
        Object.assign(uploadForm, {
          playletId: '',
          socialUserId: '',
          fileId: null,
          videoRemark: '',
          publishType: '1',
          cron: '',
          title: ''
        })
      })
  })

  //   // 重置表单
  //   Object.assign(uploadForm, {
  //     playletId: '',
  //     socialUserId: '',
  //     fileId: null,
  //     description: '',
  //     publishType: '1',
  //     cron: ''
  //   })

}

// 发布抖音
const publishLoading = ref(false)
const submitUpload = () => {
  validate().then(res => {
    publishLoading.value = true
    setTimeout(() => {
      publishLoading.value = false
      ElMessage({
        message: '提交失败',
        type: 'error'
      })
  
    }, Math.floor(Math.random() * (6000 - 4000 + 1)) + 4000)
  })
  // ElMessage.success('草稿已保存')
}

function validate() {
  return new Promise(resolve => {
    if (!uploadForm.playletId) {
      ElMessage.warning('请选择短剧')
      return
    }
    if (!uploadForm.socialUserId) {
      ElMessage.warning('请选择上传频号')
      return
    }
    if (isUploading.value) {
      ElMessage.warning('请等待视频上传完成')
      return
    }
    if (!uploadForm.fileId) {
      ElMessage.warning('请选择要上传的视频文件')
      return
    }
    if (!uploadForm.title) {
      ElMessage.warning('请输入视频标题')
      return
    }
    if (!uploadForm.videoRemark) {
      ElMessage.warning('请输入视频描述')
      return
    }
    if (uploadForm.publishType === '2') {
      if (!uploadForm.cron) {
        ElMessage.warning('请选择定时时间')
        return
      }
    }
    
    resolve()
  })
}

// 模拟上传进度
const simulateUploadProgress = (task) => {
  const timer = setInterval(() => {
    if (task.progress >= 100) {
      task.status = 'completed'
      clearInterval(timer)
      return
    }

    if (task.status === 'uploading') {
      task.progress += Math.random() * 10
      if (task.progress > 100) task.progress = 100
    }
  }, 1000)
}

// 暂停任务
const pauseTask = (row) => {
  row.status = 'paused'
  ElMessage.info(`已暂停上传: ${row.name}`)
}

// 恢复任务
const resumeTask = (row) => {
  row.status = 'uploading'
  ElMessage.success(`已恢复上传: ${row.name}`)
  simulateUploadProgress(row)
}

// 删除任务
const deleteTask = (row) => {
  const index = taskList.value.findIndex((task) => task.id === row.id)
  if (index > -1) {
    taskList.value.splice(index, 1)
    ElMessage.success(`已删除任务: ${row.name}`)
  }
}

// 分享任务
const shareTask = (row) => {
  ElMessage.success(`分享链接已复制: ${row.name}`)
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'uploading':
      return 'primary'
    case 'completed':
      return 'success'
    case 'paused':
      return 'warning'
    case 'failed':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'uploading':
      return '上传中'
    case 'completed':
      return '已完成'
    case 'paused':
      return '已暂停'
    case 'failed':
      return '上传失败'
    default:
      return '待上传'
  }
}

// 获取进度条颜色
const getProgressColor = (status) => {
  switch (status) {
    case 'uploading':
      return '#6366f1'
    case 'completed':
      return '#22c55e'
    case 'paused':
      return '#f59e0b'
    case 'failed':
      return '#ef4444'
    default:
      return '#94a3b8'
  }
}

onMounted(() => {
  // 获取社交用户
  getSocialUserPage({ pageNo: 1, pageSize: 100 }).then((res) => {
    console.log(res)
    channelOptions.value = res.list
  })
  // 获取短剧
  shortPlayApi.getList({ pageNo: 1, pageSize: 100 }).then((res) => {
    console.log(res)
    dramaOptions.value = res
  })
})

onUnmounted(() => {
  if (worker.value) {
    worker.value.terminate()
  }
})
</script>

<template>
  <div class="auto-upload-container">
    <!-- 页面标题 -->
    <!-- <div class="page-title">
      <h2>短剧自动上传</h2>
    </div> -->

    <!-- 上传配置表单 -->
    <el-card class="upload-form-card">
      <div style="width: 100%; display: flex; justify-content: center">
        <el-form :model="uploadForm" label-width="120px" class="upload-form">
          <!-- 选择短剧 -->
          <el-form-item label="选择短剧">
            <el-tree-select
              v-model="uploadForm.playletId"
              :data="dramaOptions"
              :render-after-expand="false"
              :props="{ label: 'name', value: 'id' }"
              style="width: 100%"
            />
          </el-form-item>

          <!-- 上传频号 -->
          <el-form-item label="上传抖音号">
            <el-select
              v-model="uploadForm.socialUserId"
              placeholder="请选择抖音号"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="channel in channelOptions"
                :key="channel.id"
                :label="`${channel.nickname}`"
                :value="channel.id"
              />
            </el-select>
          </el-form-item>

          <!-- 上传视频文件 -->
          <el-form-item label="上传视频文件">
            <div class="upload-area">
              <el-upload
                class="video-upload"
                ref="uploadRef"
                drag
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :accept="'.mp4,.mov'"
                :show-file-list="false"
              >
                <div class="upload-content">
                  <el-icon class="upload-icon" size="48" color="#6366f1">
                    <Upload />
                  </el-icon>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽文件到此处上传</p>
                    <p class="upload-subtitle">支持MP4、MOV视频格式，最大128M</p>
                  </div>
                </div>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="上传进度" v-if="isUploading || uploadProgress == 100">
            <el-progress
              :percentage="uploadProgress"
              :status="uploadProgress == 100 ? 'success' : ''"
            />
          </el-form-item>
          <!-- 视频标题 -->
          <el-form-item label="视频标题">
            <el-input v-model="uploadForm.title" placeholder="输入视频标题" />
          </el-form-item>

          <!-- 视频描述 -->
          <el-form-item label="视频描述">
            <el-input
              v-model="uploadForm.videoRemark"
              type="textarea"
              :rows="4"
              placeholder="输入视频描述，可包含话题标签..."
            />
          </el-form-item>

          <!-- 发布时间 -->
          <el-form-item label="发布时间">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-select
                  v-model="uploadForm.publishType"
                  placeholder="立即发布"
                  style="width: 180px"
                >
                  <el-option label="立即发布" value="1" />
                  <el-option label="定时发布" value="2" />
                </el-select>
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="uploadForm.cron"
                  type="datetime"
                  placeholder="定时发布时间"
                  style="width: 200px"
                  v-if="uploadForm.publishType === '2'"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-col>
            </el-row>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-button
                  type="primary"
                  @click="submitUpload"
                  :loading="publishLoading"
                  style="width: 100%"
                >
                  提交任务
                </el-button>
              </el-col>
              <el-col :span="12">
                <el-button @click="saveDraft" style="width: 100%" :loading="submiting"> 保存草稿 </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 上传任务队列 -->
    <!-- <el-card class="task-queue-card">
      <div class="queue-header">
        <h3>上传任务队列</h3>
      </div>
      <div style="width: 100%; display: flex; justify-content: center">
        <el-table :data="taskList" style="width: 100%" stripe>
          <el-table-column prop="name" label="剧名" />
          <el-table-column prop="fileName" label="文件" />
          <el-table-column prop="channel" label="频号" />
          <el-table-column prop="status" label="状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="300" align="center">
            <template #default="{ row }">
              <div class="progress-container">
                <el-progress
                  :percentage="row.progress"
                  :color="getProgressColor(row.status)"
                  :stroke-width="8"
                  :show-text="false"
                />
                <span class="progress-text">{{ row.progress }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  v-if="row.status === 'uploading'"
                  type="warning"
                  size="small"
                  @click="pauseTask(row)"
                  circle
                >
                  <el-icon><VideoPause /></el-icon>
                </el-button>
                <el-button
                  v-if="row.status === 'paused'"
                  type="success"
                  size="small"
                  @click="resumeTask(row)"
                  circle
                >
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
                <el-button type="danger" size="small" @click="deleteTask(row)" circle>
                  <el-icon><Delete /></el-icon>
                </el-button>
                <el-button
                  v-if="row.status === 'completed'"
                  type="primary"
                  size="small"
                  @click="shareTask(row)"
                  circle
                >
                  <el-icon><Share /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card> -->
  </div>
</template>

<style scoped>
.auto-upload-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面标题 */
.page-title {
  margin-bottom: 24px;
}

.page-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

/* 上传表单卡片 */
.upload-form-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.upload-form {
  width: 60%;
}

/* 文件上传区域 */
.upload-area {
  width: 100%;
}

.video-upload {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 20px;
  text-align: center;
}

.upload-icon {
  margin-bottom: 16px;
}

.upload-text {
  color: #666;
}

.upload-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #1a1a1a;
}

.upload-subtitle {
  font-size: 14px;
  margin: 0;
  color: #999;
}

/* 任务队列卡片 */
.task-queue-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.queue-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.queue-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

/* 进度条容器 */
.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 35px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 6px;
  min-width: 32px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 24px;
}

.el-select,
.el-input,
.el-date-picker {
  width: 100%;
}

/* 上传组件样式 */
.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: auto;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.el-upload-dragger:hover {
  border-color: #6366f1;
  background-color: #f8f9ff;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--primary {
  background-color: #6366f1;
  border-color: #6366f1;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 进度条样式 */
.el-progress {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auto-upload-container {
    padding: 10px;
  }

  .upload-content {
    padding: 40px 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .progress-container {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
